package com.bodystm.controller;

import java.io.Console;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.druid.util.StringUtils;
import com.bodystm.bean.Alarm;
import com.bodystm.bean.Bed;
import com.bodystm.bean.Patient;
import com.bodystm.bean.PatientBedUser;
import com.bodystm.bean.PatientEquip;
import com.bodystm.bean.Temperature;
import com.bodystm.service.AlarmService;
import com.bodystm.service.BedService;
import com.bodystm.service.PatientBedService;
import com.bodystm.service.PatientEquipService;
import com.bodystm.service.PatientService;
import com.bodystm.service.TemperatureService;
import com.bodystm.web.DeviceSettings;
import com.bodystm.web.EasyUiMessage;
import com.bodystm.web.TemperatureDevice;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.common.system.user.UserService;
import com.mimosa.util.config.Page;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/patient")
public class PatientController {
	@Resource 
	private UserService userService;
	@Resource 
	private PatientBedService patientBedUserService;
	@Resource
	private PatientService patientService;
	//@Resource
	//private PatientBedService patientBedService;
	@Resource
	private BedService bedService;
	@Resource
	private TemperatureService temperatureService;
	@Resource
	private PatientEquipService patientEquipService;
	@Resource
	private AlarmService alarmService;
	
	
	@RequestMapping("/index.action")
	public String index() {
		return "patient/patientManage";
	}
	
	@ResponseBody
	@RequestMapping("/getPatientById.action")
	public String getPatientById(String id) {
		Patient patient=patientService.getEntity(id);
		StringBuilder builder = new StringBuilder();
		Date date = null;
		builder.append("{\"id\":\"").append(patient.getId());
//		builder.append("\",\"bedid\":\"").append(patient.getBed()==null?"":patient.getBed().getName());
//		builder.append("\",\"idofbed\":\"").append(patient.getBed()==null?"":patient.getBed().getId());
		builder.append("\",\"name\":\"").append(patient.getName());
		builder.append("\",\"sex\":\"").append(patient.getSex());
		builder.append("\",\"age\":\"").append(patient.getAge());
		builder.append("\",\"idnumber\":\"").append(patient.getIdnumber());
		builder.append("\",\"admissionNumber\":\"").append(patient.getAdmissionNumber());
		builder.append("\",\"patientType\":\"").append(patient.getPatientType());
		builder.append("\",\"pacing\":\"").append(patient.getPacing());
//		if(patient.getListenStartTime()!=null)
//		builder.append("\",\"listentime\":\"").append(DateFormatUtils.format(patient.getListenStartTime(),"MM-dd HH:mm")+"~");
//		if(patient.getListenEndTime()!=null)
//		builder.append("\",\"listentime\":\"").append(DateFormatUtils.format(patient.getListenEndTime(),"MM-dd HH:mm"));
//		date = patient.getStartTime();
//		builder.append("\",\"roomtime\":\"");
//		if (date != null) {
//			builder.append(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
//		}
//		date = patient.getEndTime();
//		builder.append("\",\"endTime\":\"");
//		if (date != null) {
//			builder.append(DateFormatUtils.format(date, "yyyy-MM-dd"));
//		}
//		builder.append("\",\"age\":\"").append(patient.getAge());
//		builder.append("\",\"lowc\":\"").append(patient.getRangeStart());
//		builder.append("\",\"highc\":\"").append(patient.getRangeEnd());
//		builder.append("\",\"superHighDegree\":\"").append(patient.getSuperHighDegree());
//		Temperature temprature=temperatureService.getLatestTemprature(patient.getEquipNo());
//		builder.append("\",\"degree\":\"").append(temprature==null?"":temprature.getMeasureNum());
		builder.append("\",\"lastUpdateTime\":\"").append(patient.getLastUpdateTime()).append("\"}");
		return builder.toString();
	}
	/*
	 * ��ȡĳ���������еĲ���
	 * ����userId��ʾ����Id
	 */
	@ResponseBody
	@RequestMapping("/list.action")
	public String list(Page<Patient> page,String userId,String patientName) {
		DecimalFormat decimalFormat=new DecimalFormat(".00");//���췽�����ַ��ʽ�������С����2λ,����0����.
		page.setOrder(Page.ASC+","+Page.DESC);
		page.setOrderBy("endTime,startTime");
		Page<Patient> patients = this.patientService.findByPage(page,Restrictions.eq("user.id", userId));
		if(StringUtils.isEmpty(patientName)){
			patients = this.patientService.findByPage(page,Restrictions.eq("user.id", userId));
		}else{
			patients = this.patientService.findByPage(page,Restrictions.eq("user.id", userId),Restrictions.like("name", patientName, MatchMode.ANYWHERE));
		}
		//List<Patient> patients;//=page.getResult();//patientService.getAll();
		//patients=patientBedUserService.getPatientsOfDepartment(userId);
		//List<Patient> patients=patientService.getAll();
		StringBuilder builder = new StringBuilder("{\"total\":\"");
		builder.append(patients.getTotalCount());
		//builder.append(page.getTotalCount());
		builder.append("\",\"rows\":[");
		Date date = null;
		for (Patient patient : patients.getResult()) {
			builder.append("{\"id\":\"").append(patient.getId());
//			builder.append("\",\"bedid\":\"").append(patient.getBed()==null?"":patient.getBed().getName());
			builder.append("\",\"name\":\"").append(patient.getName());
			builder.append("\",\"sex\":\"").append(patient.getSex());
			if(patient.getEndTime()!=null){
				builder.append("\",\"status\":\"").append(0);
			}else{
				builder.append("\",\"status\":\"").append(1);
			}
			if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null){
				builder.append("\",\"listentime\":\"").append(DateFormatUtils.format(patient.getListenStartTime(),"MM-dd HH:mm")+"~"+DateFormatUtils.format(patient.getListenEndTime(),"MM-dd HH:mm"));
			}
				
			
			date = patient.getStartTime();
			builder.append("\",\"startTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
			}
			date = patient.getEndTime();
			builder.append("\",\"endTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
			}
			builder.append("\",\"age\":\"").append(patient.getAge());
			Temperature temprature=temperatureService.getLatestTemprature(patient.getEquipNo());
			if (DeviceSettings.lstMacs.contains(patient.getEquipNo())) {
				TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
				if (temperatureDevice.getCurrentDegree()>0) {
					builder.append("\",\"degree\":\"").append(decimalFormat.format(temperatureDevice.getCurrentDegree()));
				}else {
					builder.append("\",\"degree\":\"").append(temprature==null?"":decimalFormat.format(temprature.getMeasureNum()));
				}
			}else{
				builder.append("\",\"degree\":\"").append(temprature==null?"":decimalFormat.format(temprature.getMeasureNum()));
			}
					
			builder.append("\",\"cardnum\":\"").append(patient.getEquipNo()).append("\"},");
		}
		if(patients.getTotalCount()>0)
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]}");

		return builder.toString();
	}
	/**
	 * 病人入住
	 * 2018年1月4日22:37:14
	 * @param patient
	 * @param bedId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addPatient.action")
	public String addPatient(Patient patient,String bedId){
		JSONObject result=new JSONObject();
		try {
			Bed bed=bedService.getEntity(bedId);//获取新的床位
			if(!bed.getStatus().equals("empty")){
				result.put("success", false);
				return result.toString();
			}
			
			patient.setListenStartTime(new Date());
			bed.setStatus("notempty");
			patient.setBedId(bedId);
//		patient.setBed(bed);
			patient.setUser(bed.getUser());//
			patient.setEquipNo(bed.getConcentratorNo().toUpperCase());
			
			PatientBedUser patientBedUser=new PatientBedUser();
			patientBedUser.setBed(bed);
			patientBedUser.settUser(bed.getUser());
			patientBedUser.setPatient(patient);
			patientBedUser.setStatus(1);
			patientBedUser.setStatusOfDepartment(1);
			patientBedUser.setMac(bed.getConcentratorNo());
			//删除出院病人在list中的mac地址
			/*if (!DeviceSettings.lstMacs4CurrentPatients.contains(patient.getEquipNo())) {
				DeviceSettings.lstMacs4CurrentPatients.add(patient.getEquipNo());
			}*/
			this.patientService.saveEntity(patient);
			patientBedUserService.saveEntity(patientBedUser);
			//根据新添加的mac删除所有的该mac相关的旧数据
			//patientEquipService.deleteAllByMac(patient.getEquipNo());
			//添加设备与病人关系表记录
			/*PatientEquip patientEquip=new PatientEquip();
			patientEquip.setPatientID(patient.getId());
			patientEquip.setEquipNo(patient.getEquipNo());
			patientEquipService.saveEntity(patientEquip);*/
			//bed.setPatientId(patient.getId());
			bed.setPatient(patient);
			bedService.saveEntity(bed);
			//为了使缓存中床位信息同步更新 2018年6月24日22:26:02
			Bed bedCache = DeviceSettings.hasBeds.get(bed.getConcentratorNo());
			if(null!=bedCache){
				bedCache.setStatus("notempty");
				bedCache.setPatient(patient);
			}
//			DeviceSettings.hasBeds.remove(bed.getConcentratorNo());
			result.put("success", true);
			result.put("patientId", patient.getId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result.toString();
	}
	@ResponseBody
	@RequestMapping("/save.action")
	public String save(Patient patient,String bedName,String userId) {
		Bed bed=bedService.getBedByName(bedName,userId);//获取新的床位
		if(bed==null){
			return "{\"success\":false,\"bedstatus\":\""+null+"\"}";
		}
		TUser user=userService.getEntity(userId);//获取当前用户（科室）
		if(patient.getId()!=null&&patient.getId().length()>0){//如果是修改病人信息
			Patient patientTempOld=patientService.getEntity(patient.getId());//旧病人
			String strOldMac=patientTempOld.getEquipNo();
			patient.setListenStartTime(patientTempOld.getListenStartTime());
//			patient.setBed(bed);
			patient.setUser(user);
			patient.setEndTime(patientTempOld.getEndTime());
			
			//添加设备与病人关系表记录
			if(!strOldMac.equals(patient.getEquipNo())){//如果换了新的温度贴片,则新加病人与设备对应关系记录
				patient.setEquipNo(patient.getEquipNo().toUpperCase());
				patient.setListenStartTime(new Date());
				PatientEquip patientEquip=new PatientEquip();
				patientEquip.setEquipNo(patient.getEquipNo());
				patientEquip.setPatientID(patient.getId());
				//根据新添加的mac删除所有的该mac相关的旧数据
				patientEquipService.deleteAllByMac(patient.getEquipNo());
				patientEquipService.saveEntity(patientEquip);
				//删除旧信息，增加新信息
				if (!DeviceSettings.lstMacs4CurrentPatients.contains(patient.getEquipNo())) {
					DeviceSettings.lstMacs4CurrentPatients.add(patient.getEquipNo());
				}
				if (DeviceSettings.lstMacs4CurrentPatients.contains(strOldMac)) {
					DeviceSettings.lstMacs4CurrentPatients.remove(strOldMac);
				}
				//替换新贴片时将上个贴片的温度数据存储到新的贴片信息中
				try {
					//判断全局变量中是否含有此设备，没有则新建，有则获取
					TemperatureDevice temperatureDevice=null;
					float olddegree=0;
					if(DeviceSettings.lstMacs.contains(patient.getEquipNo())){
						temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
					}else{
						DeviceSettings.lstMacs.add(patient.getEquipNo());
						temperatureDevice=new TemperatureDevice();
						temperatureDevice.setStrMac(patient.getEquipNo());
						DeviceSettings.hasDevice.put(patient.getEquipNo(), temperatureDevice);
					}
					if(DeviceSettings.lstMacs.contains(strOldMac)){
						olddegree=((TemperatureDevice)DeviceSettings.hasDevice.get(strOldMac)).getCurrentDegree();
						if (olddegree>34) {
							temperatureDevice.setDegree4LastMac(olddegree);
						}
					}
					DeviceSettings.lstMacs.remove(strOldMac);
					DeviceSettings.hasDevice.remove(strOldMac);
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			//判断是否修改了床位信息
			//patientTempOld.getBed().getName().equals(bedName)
			if(true){//如果床位没有变，只修改了基本信息，则直接存储
				this.patientService.saveEntity(patient);
			}else{//如果修改了床位
				Bed bedTempOld=null;//bedService.getBedByName(patientTempOld.getBed().getName(),userId);2018年1月8日23:35:50
				if(!bed.getStatus().equals("empty")){//判断新的床位是否已经有病人，如果有病人则交换床位
					PatientBedUser pbu2=patientBedUserService.getPatientBedUserByBedName(bedName);//要与其交换的病人关系记录
//					pbu2.getPatient().setBed(bedTempOld);
					this.patientService.saveEntity(pbu2.getPatient());
					this.patientService.saveEntity(patient);
					pbu2.setBed(bedTempOld);
					patientBedUserService.saveEntity(pbu2);
				}else{//如果是换空床
					this.patientService.saveEntity(patient);
					bedTempOld.setStatus("empty");
					bed.setStatus("notempty");
					bedService.saveEntity(bedTempOld);
				}
				PatientBedUser patientBedUserOld=patientBedUserService.getPatientBedUserByPatientAnddBed(patient.getId(), bedTempOld.getId());
				if(patientBedUserOld!=null){
					patientBedUserOld.setBed(bed);
					patientBedUserOld.setPatient(patient);//为了保存新的病人的信息					
					patientBedUserService.saveEntity(patientBedUserOld);
				}

			}	
		}else{//新加病人
			if(!bed.getStatus().equals("empty")) return "{\"success\":false,\"bedstatus\":\""+bed.getStatus()+"\"}";
			patient.setListenStartTime(new Date());
			bed.setStatus("notempty");
//			patient.setBed(bed);
			patient.setUser(user);//
			/*patient.setListenStartTime(new Date());*/
			patient.setEquipNo(patient.getEquipNo().toUpperCase());
			
			PatientBedUser patientBedUser=new PatientBedUser();
			patientBedUser.setBed(bed);
			patientBedUser.settUser(user);
			patientBedUser.setPatient(patient);
			patientBedUser.setStatus(1);
			patientBedUser.setStatusOfDepartment(1);
			
			//删除出院病人在list中的mac地址
			if (!DeviceSettings.lstMacs4CurrentPatients.contains(patient.getEquipNo())) {
				DeviceSettings.lstMacs4CurrentPatients.add(patient.getEquipNo());
			}
			this.patientService.saveEntity(patient);
			patientBedUserService.saveEntity(patientBedUser);
			//根据新添加的mac删除所有的该mac相关的旧数据
			patientEquipService.deleteAllByMac(patient.getEquipNo());
			//添加设备与病人关系表记录
			PatientEquip patientEquip=new PatientEquip();
			patientEquip.setPatientID(patient.getId());
			patientEquip.setEquipNo(patient.getEquipNo());
			patientEquipService.saveEntity(patientEquip);
		}
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return "{\"success\":true}";
	}
	@ResponseBody
	@RequestMapping("/ifExitsTheMac.action")
	public String ifExitsTheMac(String mac) {
		List<PatientEquip> lstPEs=patientEquipService.getPatientEquipByMac(mac);
		if(lstPEs==null||lstPEs.size()==0){
			return "{\"exist\":false}";
		}
		return "{\"exist\":true}";
	}

	@ResponseBody
	@RequestMapping("/update.action")
	public String update(Patient patient,String mac) {
		Bed bed=bedService.getPatientIdBybed(mac);
		patient.setBedId(bed.getId());
		this.patientService.saveEntity(patient);
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		//查询报警初始化数据放入内存中
		List<Alarm> list=alarmService.getAlarmByPatientId(patient.getPatientType());
		DeviceSettings.AlarmDevice.put(mac, list);
		DeviceSettings.AlarmDevice.put("state", "0");
		DeviceSettings.AlarmDevice.put("time", new Date());
		return Boolean.TRUE.toString().toLowerCase();
	}
	
	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Patient patient,String bedname,HttpSession session) {
		Bed bed=bedService.getBedByName(bedname,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		if(bed!=null){
		bed.setStatus("empty");
		bedService.saveEntity(bed);
		}
		try {
			this.patientBedUserService.deleteByPatientId(patient.getId());
			patientEquipService.deleteByPatientId(patient.getId());//删除病人贴片关系表数据 20160726
			//删除出院病人在list中的mac地址
			if (DeviceSettings.lstMacs4CurrentPatients.contains(patient.getEquipNo())) {
				DeviceSettings.lstMacs4CurrentPatients.remove(patient.getEquipNo());
			}
			this.patientService.deleteEntity(patient);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return new EasyUiMessage().toString();
	}
	
	/**
	 * 修正数据
	 * @param strMac
	 * @param correctNum
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/correctDegree.action")
	public String correctDegree(String strMac,float correctNum) {
		Patient patient=this.patientService.getPatientByMac(strMac);
		if(patient!=null){
			patient.setNum4Correct(correctNum);
			patientService.saveEntity(patient);
			if(DeviceSettings.lstMacs.contains(strMac)){
				TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strMac);
				temperatureDevice.setNum4Correct(correctNum);
			}else{
				DeviceSettings.lstMacs.add(strMac);
				TemperatureDevice temperatureDevice=new TemperatureDevice();
				temperatureDevice.setNum4Correct(correctNum);
				temperatureDevice.setStrMac(strMac);
				DeviceSettings.hasDevice.put(strMac, temperatureDevice);
			}
			return Boolean.TRUE.toString().toLowerCase();
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	//---------------------------2018年3月14日20:13:28-------------------------------
	/**
	 * 更新病人姓名以及报警值等基础信息
	 * @param patient
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateBasicInfo.action")
	public String updateBasicInfo(Patient patient) {
		Patient patientTempOld=patientService.getEntity(patient.getId());//旧病人
		if (null==patientTempOld) {
			return Boolean.FALSE.toString().toLowerCase();
		}else{
			patientTempOld.setAdmissionNumber(patient.getAdmissionNumber());
			patientTempOld.setName(patient.getName());
			patientTempOld.setRangeStart(patient.getRangeStart());
			patientTempOld.setRangeEnd(patient.getRangeEnd());
			patientTempOld.setSuperHighDegree(patient.getSuperHighDegree());
			patientTempOld.setSpo2LowAlarmValue(patient.getSpo2LowAlarmValue());
			patientTempOld.setSpo2HighAlarmValue(patient.getSpo2HighAlarmValue());
			patientTempOld.setHrLowAlarmValue(patient.getHrLowAlarmValue());
			patientTempOld.setHrHighAlarmValue(patient.getHrHighAlarmValue());
			this.patientService.saveEntity(patientTempOld);
		}

		return Boolean.TRUE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/getPatient.action")
	public String getPatient(String id) {
		Patient patient=patientService.getEntity(id);
		JSONObject json=new JSONObject();
		json.put("id", patient.getId());
		json.put("admissionNumber", patient.getAdmissionNumber());
		json.put("name", patient.getName());
		json.put("rangeStart", patient.getRangeStart());
		json.put("rangeEnd", patient.getRangeEnd());
		json.put("superHighDegree", patient.getSuperHighDegree());
		json.put("spo2LowAlarmValue", patient.getSpo2LowAlarmValue());
		json.put("spo2HighAlarmValue", patient.getSpo2HighAlarmValue());
		json.put("hrLowAlarmValue", patient.getHrLowAlarmValue());
		json.put("hrHighAlarmValue", patient.getHrHighAlarmValue());
		return json.toString();
	}
}